//
//  AddThingView.swift
//  VenusTodo
//
//  Created by 文显庆 on 2021/10/7.
//

//添加任务视图
import SwiftUI
struct AddThingView: View {
    var preView: TodoView //存储跳转之前的View
    var TaskTypes = ["定量任务", "打卡任务"]
    var colors = [Color.blue, Color.purple, Color.red, Color.pink, Color.black, Color.orange]
    var myDateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }
    @State var isPressed_Pop = false
    @State var selectItemTask = 0 // 任务索引
    @State var selectColorTask = 0 // 图标颜色索引
    @State var formatedDateStart = "" //格式化后的开始日期
    @State var formatedDateEnd = "" //格式化后的结束日期
    //错误提示信息
    @State private var errorShowing = false
    @State private var errorTitle = ""
    @State private var errorMessage = ""  //错误提示信息
    var bindingDateStart: Binding<Date> {
        Binding<Date> (get: { Date() }, set: {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy年MM月dd日"
            formatedDateStart = formatter.string(from: $0)
        }) //当用户选择日期时，对所选日期进行格式化
    }
    var bindingDateEnd: Binding<Date> {
        Binding<Date> (get: { Date() }, set: {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy年MM月dd日"
            formatedDateEnd = formatter.string(from: $0)
        }) //当用户选择日期时，对所选日期进行格式化
    }
    @State var taskName : String = ""  //任务名称
    @State var additional: String = "" //附加信息
    @State var target: String = "" //任务目标
    @State var wakeUp = Date()
    @State var startDate: Date = Date()
    @State var endDate: Date = Date()
    var body: some View {
            List {
                Section(header: Text("选择任务类型")){
                    HStack(){
                        //Text("") + Text("\(TaskTypes[selectItemTask])")
                        
                        Picker(selection: $selectItemTask, label: Text("任务类型")){
                            ForEach(0 ..< TaskTypes.count) {
                                Text(self.TaskTypes[$0]).tag($0)
                            }
                        }.frame(width: 350, height: 150)
                    }
                }
                Section(header: Text("任务目标")){
                    HStack {
                        TextField("请输入目标", text: $target, onEditingChanged: { (value) in print("onEditingChanged:\(self.target)")}
                        )
                    }
                }
                Section(header: Text("选择Tag颜色")){
                    HStack{
                        Image(systemName: "circle.fill").foregroundColor(self.colors[selectColorTask])

                        Picker(selection: $selectColorTask, label: Text("任务颜色")){
                            ForEach(0 ..< colors.count) {
                                Image(systemName: "rectangle.fill").foregroundColor(self.colors[$0])
                            }
                        }.frame(width: 350, height: 130)
                    }
                }
                Section(header: Text("开始日期")){
                    VStack{
                        DatePicker(selection: bindingDateStart, in: Date()...Date().advanced(by: 365*24*3600),  displayedComponents: [.date, .hourAndMinute]) {
                            Image(systemName: "calendar.circle")
                        }
                        Text("开始日期: \(formatedDateStart)").font(.caption)
                    }
                }
                Section(header: Text("结束日期")){
                    VStack{
                        DatePicker(selection: bindingDateEnd, in: Date()...Date().advanced(by: 365*24*3600),  displayedComponents: [.date, .hourAndMinute]) {
                            Image(systemName: "calendar.circle.fill")
                        }
                        Text("结束日期: \(formatedDateEnd)").font(.caption)
                    }
                }
                Section(header: Text("任务名称")){
                    HStack {
                        TextField("请输入任务名称", text: $taskName, onEditingChanged: { (value) in print("onEditingChanged:\(self.taskName)")}
                        )
                    }
                }
                Section(header: Text("任务说明")){
                    HStack {
                        TextField("请输入任务说明", text: $additional, onEditingChanged: { (value) in print("onEditingChanged:\(self.additional)")}
                        )
                    }
                }
                
                
                Button("确认提交") {
                    if(self.taskName == ""){
                        self.errorShowing = true
                        self.errorTitle = "无效的名称"
                        self.errorMessage = "请检查您的任务名称"
                        return
                    }else if(self.formatedDateEnd == "" || self.formatedDateStart == ""){
                        self.errorShowing = true
                        self.errorTitle = "无效的日期"
                        self.errorMessage = "请检查您日期选择"
                        return
                    }else if(self.target == ""){
                        self.errorShowing = true
                        self.errorTitle = "无效的目标"
                        self.errorMessage = "请检查您的任务目标"
                        return
                    }else{
                        self.isPressed_Pop = true
                        self.addTask(SD: formatedDateStart, ED: formatedDateEnd)
                        self.save()
                    }
                }.sheet(isPresented: $isPressed_Pop, content: {
                    POPView(preView: self,isPopup: .constant(true))
                } )
                .padding(10.0)
                .foregroundColor(.white)
                .background(Color.blue)
                .cornerRadius(8)
            }.alert(isPresented: $errorShowing, content: {
                Alert(title: Text(errorTitle),  message: Text(errorMessage), dismissButton: .default(Text("确认")))
            })
        
        
    }
    func addTask(SD: String, ED: String) {
        
        var newTask = ThingsTodo(isDone: false, id: id_tag, name: taskName, type: 0, startDate: bindingDateStart.wrappedValue, endDate: bindingDateEnd.wrappedValue, additional: self.additional, taskIndex: selectItemTask, colorIndex: selectColorTask)
        print("ed: \(ED)")
        newTask.formatedDateStart = SD
        newTask.formatedDateEnd = ED
        if self.selectItemTask == 0 {
            newTask.target = Int(self.target)!
        } else {
            newTask.isDone = false
        }
        self.preView.Tasks.append(newTask)
        //self.preView.isPressed_addView.toggle()
        id_tag += 1
        
        print("Successfully added")
    }
    
    //本地存储数据
    func save() {
        do{
            let data = try JSONEncoder().encode(self.preView.Tasks)
            UserDefaults.standard.setValue(data, forKey: "Tasks")
        }catch {
            print("Error")
        }
    }
}

/*
#if DEBUG
struct AddThingView_Previews: PreviewProvider {
    static var previews: some View {
        AddThingView(preView: TodoView())
    }
}
#endif
 */
/*
struct ContentView : View {
    
    @State var username : String //用于接收用户在TextField中输入的内容，并在左侧添加@state关键词
//@State是指属性代理，它表示username属性将和界面上的元素进行绑定。当属性的值发生变化时，SwiftUI会立即通知绑定的视觉元素进行内容的更新
    @State var nickname : String
    
    var body: some View {
        
        VStack{
            
            Text("Your username is \(username)!") //由于username属性拥有@State标记，所以一旦username属性的值发生变化，文本视图上的文字内容也会立即刷新
            
            Text("Your nickname is \(nickname)!")
            
            TextField("User Name", text: $username, onEditingChanged: { (value) in //设置text属性为username的值，$是指Binding wrapper绑定包装，表示可以修改属性的值
                print("onEditingChanged:\(self.username)") //当用户修改文本输入框里的内容时，在控制台输出属性的值，实时观察属性的值的变化
            }) {
                print("onCommit:\(self.username)") //当用户完成文本框里的输入时，在控制台输出username属性的值
            }.textFieldStyle(RoundedBorderTextFieldStyle()) //设置TextField的样式为圆角边框样式
            
            TextField("Nick Name", text: $nickname)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            
        }
        .padding()
        //只有实时预览模式才可以和界面中的元素进行交互
    } //通过绑定包装特性，即可实现界面元素和数据内容的实时绑定
}

if DEBUG
struct ContentView_Previews : PreviewProvider {
    
    static var previews: some View {
        ContentView(username: "", nickname: "") //由于给ContentView结构体添加了两个属性，所以需要更新PreviewProvider的属性的值，这样才可以在右侧的预览窗口显示正确的内容
    }
}
endif
 */
